<?php
core::load_class('init', 'admin');
class admin_control extends init_control {
	public function _initialize() {
		parent::_initialize();
		helper('attachment');
		$this->service = model('attachment/attachment', 'service');
	}

	public function index() {
		$spaces = array('goods' => '商品图库','article' => '文章图库','member' => '会员图库','common' => '其它图库');
		$attachments = array();
		foreach ($spaces as $key => $value) {
			$v = array();
			$v['datetime'] = (int) model('attachment', 'table')->where(array("module" => $key))->order("aid DESC")->getField('datetime');
			$v['count'] = model('attachment', 'table')->where(array("module" => $key))->count();
			$filesize = (int) model('attachment', 'table')->where(array("module" => $key))->sum("filesize");
			$v['filesize'] = sizecount($filesize);
			list($v['filesize'], $v['fileunit']) = explode(" ", $v['filesize']);
			$attachments[$key] = $v;
		}
		include $this->admin_tpl('attachment_index');
	}

	public function manage() {
		$sqlmap = array();
		$sqlmap['module']  = $_GET['folder'];
		$sqlmap['isimage'] = 1;
		if(isset($_GET['type']) && $_GET['type'] == 'use') {
			$sqlmap['use_nums'] = 0;
		}
		$limit = (isset($_GET['limit']) && is_numeric($_GET['limit'])) ? $_GET['limit'] : 20;
		$lists = model('attachment')->where($sqlmap)->limit($limit)->page($_GET['page'])->order('aid DESC')->select();
		$count = model('attachment')->where($sqlmap)->count();
		$pages = $this->admin_pages($count, $limit);
		include $this->admin_tpl('attachment_manage');
	}

	public function replace() {
		if(IS_POST) {
			$file = (isset($_GET['file'])) ? $_GET['file'] : 'upfile';
			$code = attachment_init(array('mid' => 1));
			$result = $this->service->setConfig($code)->replace($file, $_GET['aid']);
			if($result === FALSE) {
				showmessage($this->service->error);
			} else {
				showmessage('上传成功', '', 1, $result, 'json');
			}
		}
	}

	public function delete() {
		$aids = (array) $_GET['aid'];
		if(empty($aids)) {
			showmessage('请指定要删除的图片');
		}
		foreach ($aids as $aid) {
			$this->service->delete($aid);
		}
		showmessage('图片删除成功', -1, 1);
	}
}